package com.cyd.custom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cyd.homefamily.R;

@SuppressLint("InflateParams")
public class ToastUtil {
	private static Toast toast;
	private static TextView message;
	private static final int SHOW_WHAT = 0;
	private static final String TEXT = "TEXT";
	private static Context mContext;

	public static ToastUtil getInstance(Context context) {
		mContext = context;
		return new ToastUtil(context);
	}

	private ToastUtil(Context context) {
		View v = LayoutInflater.from(context).inflate(R.layout.toast, null);
		message = (TextView) v.findViewById(R.id.toast);
		toast = new Toast(context);
		toast.setView(v);
		toast.setGravity(Gravity.BOTTOM, 0, 20);
		toast.setDuration(Toast.LENGTH_SHORT);

	}

	private static Handler baseHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_WHAT:
				showToast(msg.getData().getString(TEXT));
				break;
			default:
				break;
			}

		};
	};

	public static void showToast(String text) {
		if (!TextUtils.isEmpty(text)) {
			message.setText(text);
			toast.show();
		}
	}

	public void showToast(int resId) {
		if (resId != 0) {
			message.setText(resId);
			toast.show();
		}
	}

	public void showToastInThread(String text) {
		Message msg = Message.obtain(baseHandler);
		msg.what = SHOW_WHAT;
		Bundle bundle = new Bundle();
		bundle.putString(TEXT, text);
		msg.setData(bundle);
		baseHandler.sendMessage(msg);
	}

	public void showToastInThread(int resId) {
		Message msg = Message.obtain(baseHandler);
		msg.what = SHOW_WHAT;
		Bundle bundle = new Bundle();
		bundle.putString(TEXT, mContext.getResources().getString(resId));
		msg.setData(bundle);
		baseHandler.sendMessage(msg);
	}
}
